package club.xcgame520.picturepicker;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.github.chrisbanes.photoview.OnPhotoTapListener;
import com.github.chrisbanes.photoview.PhotoView;
import club.xcgame520.picturepicker.bean.Picture;
import club.xcgame520.picturepicker.view.PicturePager;

import java.io.File;
import java.util.ArrayList;

public class PicturePreviewActivity extends AppCompatActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener, ViewPager.OnPageChangeListener {

    private ArrayList<Picture> pictureList;
    private ArrayList<Picture> selectPictureList;
    private int maxSelectNumber;
    private int currentShowIndex;

    private Toolbar tTitle;
    private TextView tvComplete;

    private RelativeLayout rlOperation;

    private TextView tvCount;
    private CheckBox cbCheck;

    private PicturePager ppPicture;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picture_preview);

        if (savedInstanceState == null) {
            maxSelectNumber = getIntent().getIntExtra("maxSelectNumber", 0);
            pictureList = (ArrayList<Picture>) getIntent().getSerializableExtra("pictureList");
            selectPictureList = (ArrayList<Picture>) getIntent().getSerializableExtra("selectPictureList");
            currentShowIndex = getIntent().getIntExtra("currentShowIndex", 0);
        } else {
            maxSelectNumber = savedInstanceState.getInt("maxSelectNumber", 0);
            currentShowIndex = savedInstanceState.getInt("currentShowIndex", 0);
            pictureList = (ArrayList<Picture>) savedInstanceState.getSerializable("pictureList");
            selectPictureList = (ArrayList<Picture>) savedInstanceState.getSerializable("selectPictureList");
        }

        tTitle = findViewById(R.id.tTitle);
        setSupportActionBar(tTitle);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        tTitle.setNavigationIcon(R.drawable.vector_action_back);

        tvComplete = findViewById(R.id.tvComplete);
        tvComplete.setOnClickListener(this);

        rlOperation = findViewById(R.id.rlOperation);

        tvCount = findViewById(R.id.tvCount);
        cbCheck = findViewById(R.id.cbCheck);

        ppPicture = findViewById(R.id.ppPictures);
        ppPicture.addOnPageChangeListener(this);
        ppPicture.setAdapter(new PicturePreviewAdapter());

        ppPicture.setCurrentItem(currentShowIndex);
        tvCount.setText((currentShowIndex + 1) + "/" + pictureList.size());

        if (selectPictureList.size() > 0) {
            tvComplete.setEnabled(true);
            tvComplete.setText("完成(" + selectPictureList.size() + "/" + maxSelectNumber + ")");
            cbCheck.setChecked(checkIsContains(pictureList.get(currentShowIndex)));
        } else {
            tvComplete.setEnabled(false);
            tvComplete.setText("完成");
        }

        cbCheck.setOnCheckedChangeListener(this);

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putSerializable("pictureList", pictureList);
        outState.putSerializable("selectPictureList", selectPictureList);
        outState.putInt("maxSelectNumber", maxSelectNumber);
        outState.putInt("currentShowIndex", currentShowIndex);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tvComplete) {
            Intent intent = getIntent();
            intent.putExtra("selectPictureList", selectPictureList);
            setResult(RESULT_OK, intent);
            finish();
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        currentShowIndex = position;
        tvCount.setText((currentShowIndex + 1) + "/" + pictureList.size());
        Picture picture = pictureList.get(position);
        cbCheck.setChecked(checkIsContains(picture));
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

        if (b) {

            if (selectPictureList.size() >= maxSelectNumber) {
                cbCheck.setChecked(false);
                Toast.makeText(this, "最多选择" + maxSelectNumber + "张图片！", Toast.LENGTH_LONG).show();
                return;

            } else {
                Picture picture = pictureList.get(currentShowIndex);
                int selectIndex = searchPictureIndex(picture);
                if (selectIndex == -1) {
                    selectPictureList.add(picture);
                }
            }

        } else {
            Picture picture = pictureList.get(currentShowIndex);
            int selectIndex = searchPictureIndex(picture);
            if (selectIndex != -1) {
                selectPictureList.remove(selectIndex);
            }
        }

        if (selectPictureList.size() > 0) {
            tvComplete.setEnabled(true);
            tvComplete.setText("完成(" + selectPictureList.size() + "/" + maxSelectNumber + ")");
            cbCheck.setChecked(checkIsContains(pictureList.get(currentShowIndex)));
        } else {
            tvComplete.setEnabled(false);
            tvComplete.setText("完成");
        }

    }

    @Override
    public void onBackPressed() {
        Log.d("发送", selectPictureList.toString());
        Intent intent = new Intent();
        intent.putExtra("selectPictureList", selectPictureList);
        setResult(RESULT_CANCELED, intent);
        super.onBackPressed();
    }

    public void setShowBar(boolean isShowBar) {
        if (isShowBar) {
            WindowManager.LayoutParams attr = getWindow().getAttributes();
            attr.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(attr);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        } else {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            getWindow().setAttributes(lp);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        }
        tTitle.setVisibility(isShowBar ? View.VISIBLE : View.GONE);
        rlOperation.setVisibility(isShowBar ? View.VISIBLE : View.GONE);
    }

    private boolean checkIsContains(Picture picture) {
        boolean isCheck = false;
        for (Picture selectPicture : selectPictureList) {
            if (selectPicture.getPath().equals(picture.getPath())) {
                isCheck = true;
                break;
            }
        }
        return isCheck;
    }

    private int searchPictureIndex(Picture picture) {
        for (int i = 0; i < selectPictureList.size(); i++) {
            if (selectPictureList.get(i).getPath().equals(picture.getPath())) {
                return i;
            }
        }
        return -1;
    }

    private class PicturePreviewAdapter extends PagerAdapter {

        private boolean isShowBar = true;

        @Override
        public int getCount() {
            return pictureList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {

            View view = LayoutInflater.from(PicturePreviewActivity.this).inflate(R.layout.view_item_picture_preview, container, false);
            PhotoView pvPicture = view.findViewById(R.id.pvPicture);

            Glide.with(PicturePreviewActivity.this).load(new File(pictureList.get(position).getPath())).apply(new RequestOptions()
                    .placeholder(R.mipmap.pp_placeholder)
                    .error(R.mipmap.pp_placeholder))
                    .into(pvPicture);

            pvPicture.setOnPhotoTapListener(new OnPhotoTapListener() {
                @Override
                public void onPhotoTap(ImageView view, float x, float y) {
                    if (isShowBar) {
                        isShowBar = false;
                    } else {
                        isShowBar = true;
                    }
                    setShowBar(isShowBar);
                }
            });

            container.addView(view);
            Log.d("WxPicturePreview", "实例化item");
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
            Log.d("WxPicturePreview", "销毁item");
        }
    }

}
